package controllers

import (
	"encoding/json"
	"net/url"
	"odooapp/app/odooapi"

	"github.com/revel/revel"
)

type Auth struct {
	*revel.Controller
}

// @Login
// @Description	   Login odoo: if session_id is contained in params, rebuild client.
// @auth	zewenh
// @param   post username & password by application/json
// @return
func (c Auth) Login() revel.Result {
	respData := make(map[string]interface{})
	var jsonData map[string]interface{}
	c.Params.BindJSON(&jsonData)
	var user, password string
	if u, ok := jsonData["username"]; ok {
		user = u.(string)
	}
	if p, ok := jsonData["password"]; ok {
		password = p.(string)
	}

	client, err := odooapi.ClientConnect("testing", user, password)
	if err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = err.Error()
		return c.RenderJSON(respData)
	}
	jsonAuth, err := json.Marshal(client.Auth)
	if err != nil {
		respData["isSuccess"] = false
		respData["errMsg"] = "Odd auth response is not json type."
		return c.RenderJSON(respData)
	}

	respData["jsonAuth"] = string(jsonAuth) // convert []byte to string
	u, _ := url.Parse(client.BaseURL)
	cookies := client.HttpClient.Jar.Cookies(u)
	for _, cookie := range cookies {
		respData[cookie.Name] = cookie.Value
	}
	respData["isSuccess"] = true
	return c.RenderJSON(respData)
}

func (c Auth) Logout() revel.Result {
	return nil
}
